Project Overview

From a high level vantage, this is an image classification project.
With image classification, the input is an image and the output is a class.
Here, the problem domain is narrowed to the domain of dogs.
Specifically the intent is to input an image of a dog and output the dog breed.
This is a popular project of Udacity's, featured in many nanodegree programs.
The data set is curated by Udacity upon their project workspace.
This data set consists of over 8000 dog images from 133 breeds.
Additional input data includes uploaded image file aquired from a camera phone.

Problem Statement

Given a picture, identify if it contains a dog, and if so - reveal it's likely breed;
in the case no dog was found, search to see if it contains a human face and if so,
reveal a dog breed of similarity to the face; otherwise reveal that neither a dog
nor a face was found. Here an algorithm is developed to address this aim.

A typical strategy to building classifiers is to use supervised learning.
Here, a data set of images with known class names is used to build a classification model.
The known data is split into train, validation, and test portions which are used to
optimize the performance of the classifier by tuning weight parameters in the model.
Various models are attempted, from simple to complex until a satisfactory result is found.
In this project a simple convolutional neural network is attempted, followed by the approach
of adopting pre-trained models tailored to classify dog breeds well. As the complexity
of the models increases, the performance improves, culminating in amazing results.

Model Metrics

In this work the main metric used is accuracy.
That is, when test data is run through a model,
accuracy is the percentage of correct predictions
out of all predictions.
Accuracy figures are typically given in percentage.
Attempts are made to optimize accuracy, within reason.
For Classifiers, Precision and Recall are also used.
These give a sense of false negatives and positives.
However in the context of Dogs this isn't critical.
An accurate Dog breed assessment is done by DNA testing.

Data Scientist Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App

This notebook walks you through one of the most popular Udacity projects across machine learning and artificial intellegence nanodegree programs. The goal is to classify images of dogs according to their breed.

If you are looking for a more guided capstone project related to deep learning and convolutional neural networks, this might be just it. Notice that even if you follow the notebook to creating your classifier, you must still create a blog post or deploy an application to fulfill the requirements of the capstone project.

Also notice, you may be able to use only parts of this notebook (for example certain coding portions or the data) without completing all parts and still meet all requirements of the capstone project.


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
import pandas as pd
from glob import glob
import os
import PIL
from PIL import Image
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
from matplotlib import image as mplim
%matplotlib inline
%config InlineBackend.figure_format='retina'
import seaborn as sb
sb.set_style("darkgrid")
Using TensorFlow backend.
In [2]:
# define function to load train, test, and validation datasets
def load_dataset(path):
    '''
    import a data path based upon udacity curated dataset
    load data files using sklearn utility
    return files and corresponding targets
    '''
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('../../../data/dog_images/train')
valid_files, valid_targets = load_dataset('../../../data/dog_images/valid')
test_files, test_targets = load_dataset('../../../data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("../../../data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [3]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("../../../data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Data Exloration and Visualization, Image Count by Breed

In [4]:
# Data Representation of Breed Counts
nnames = [s.split('.')[1] for s in dog_names]
train_breeds = np.asarray([nnames[np.argmax(train_targets[i])] for i in range(len(train_targets))])
valid_breeds = np.asarray([nnames[np.argmax(valid_targets[i])] for i in range(len(valid_targets))])
test_breeds = np.asarray([nnames[np.argmax(test_targets[i])] for i in range(len(test_targets))])
cnt_trn = []
cnt_val = []
cnt_tst = []
for name in nnames:
    cnt_trn.append(np.sum(train_breeds==name))
    cnt_val.append(np.sum(valid_breeds==name))
    cnt_tst.append(np.sum(test_breeds==name))
cnt_sum = [sum(x) for x in zip(cnt_trn, cnt_val, cnt_tst)]
df_breed = pd.DataFrame.from_dict({'name': nnames,
                                   'train': cnt_trn,
                                   'valid': cnt_val,
                                   'test': cnt_tst,
                                   'total': cnt_sum,
                                  })
df_breed = df_breed.sort_values(by='total', ascending=False)
df_breed = df_breed.drop(['total'], axis=1)
df_breed = df_breed.reset_index(drop=True)
df_breed.head()
Out[4]:
name train valid test
0 Alaskan_malamute 77 9 10
1 Border_collie 74 9 10
2 Basset_hound 73 9 10
3 Dalmatian 71 9 9
4 Bull_terrier 69 9 9
In [5]:
# Median Image Count Dog Breed
df_breed.iloc[66]['name']
Out[5]:
'Anatolian_shepherd_dog'
In [6]:
# Breed Count Statistics
df_breed.describe()
Out[6]:
train valid test
count 133.000000 133.000000 133.000000
mean 50.225564 6.278195 6.285714
std 11.863885 1.350384 1.712571
min 26.000000 4.000000 3.000000
25% 42.000000 6.000000 5.000000
50% 50.000000 6.000000 6.000000
75% 61.000000 7.000000 8.000000
max 77.000000 9.000000 10.000000

Image Count Reflection:

The test and validation sets are roughly similar.
The train set is roughly 8x the size of the others.
The breed with the most images contains ~3x more
than the breed with the least.

In [7]:
fig, ax1 = plt.subplots(1,1, figsize=(7, 12), dpi=120)
df_breed.plot.barh(x = 'name', stacked=True,
                   fontsize = 5, ax = ax1, 
                   alpha = 0.5)
ax1.set_xticks(ticks=list(range(0,110,10)), minor=False)
plt.title('Data Representation: Dog Breed vs. Image Count')
plt.xlabel('Image Count')
plt.ylabel('Dog Breed')
plt.show();

Visualization Reflection:

The Alaskan Malamute has the most images at ~96 counted.
The Xoloitzcuintli has fewest images at ~33 counted.
The median Anatolian_shepherd_dog has ~63 images counted.

Data Exloration and Visualization, Image File Size by Breed

In [8]:
# Data Representation of Image File Sizes
# Find median file sizes by breed and data set
train_size = np.asarray([os.stat(i).st_size for i in train_files])
valid_size = np.asarray([os.stat(i).st_size for i in valid_files])
test_size = np.asarray([os.stat(i).st_size for i in test_files])
byt_trn = []
byt_val = []
byt_tst = []
for name in nnames:
    #train
    trn_szs = np.where(train_breeds==name, train_size, 0)
    trn_szs_m = np.ma.masked_equal(trn_szs, 0)
    byt_trn.append(np.ma.median(trn_szs_m,axis=0))
    #validate
    val_szs = np.where(valid_breeds==name, valid_size, 0)
    val_szs_m = np.ma.masked_equal(val_szs, 0)
    byt_val.append(np.ma.median(val_szs_m,axis=0))
    #test
    tst_szs = np.where(test_breeds==name, test_size, 0)
    tst_szs_m = np.ma.masked_equal(tst_szs, 0)
    byt_tst.append(np.ma.median(tst_szs_m,axis=0))
byt_sum = [sum(x) for x in zip(byt_trn, byt_val, byt_tst)]
df_bytes = pd.DataFrame.from_dict({'name': nnames,
                                   'train': byt_trn,
                                   'valid': byt_val,
                                   'test':  byt_tst,
                                   'total': byt_sum,
                                  })
df_bytes = df_bytes.sort_values(by='total', ascending=False)
df_bytes = df_bytes.drop(['total'], axis=1)
df_bytes = df_bytes.reset_index(drop=True)
df_bytes.head()    
Out[8]:
name train valid test
0 Yorkshire_terrier 121949.0 188807.5 215495.0
1 Belgian_tervuren 36462.0 163635.0 324972.5
2 Greyhound 178811.0 165991.0 169492.0
3 Otterhound 154335.0 152180.0 190213.5
4 Lowchen 134256.5 120151.5 225110.0
In [9]:
# Median Image Size Dog Breed
df_bytes.iloc[66]['name']
Out[9]:
'French_bulldog'
In [10]:
# Median Image File Byte Size Statistics
df_bytes.describe()
Out[10]:
train valid test
count 133.000000 133.000000 133.000000
mean 85713.263158 89355.187970 93535.424812
std 36196.749375 46868.424722 52310.677599
min 34000.000000 20500.500000 25411.000000
25% 51064.000000 50274.500000 51889.000000
50% 84187.000000 80854.000000 81969.000000
75% 113310.000000 129604.500000 123517.000000
max 184305.000000 195115.000000 324972.500000

Image size Reflection:

The median of the medians seems similar at ~82 kb.
The smalest image is 20 kb, the largest 325 kb.
The total median bytes varies from 110 kb to 526 kb.
Equalizing data disparity perfectly seems unlikely.
Fundamentally, the data set is imbalanced.
We expect some breeds to test better than others.

In [11]:
fig, ax1 = plt.subplots(1,1, figsize=(7, 12), dpi=120)
df_bytes.plot.barh(x = 'name', stacked=True,
                   fontsize = 6, ax = ax1, 
                   alpha = 0.5)
plt.title('Median Image File Size by Dog Breed')
plt.ylabel('Dog Breed')
plt.xlabel('Bytes')
plt.show();

Visualization Reflection:

The images for the Yorshire Terrier tend to be the largest.
The images for the American Water Spaniel seem to be the smallest.
The French Bulldog sits in the middle of the pack at ~270 kb
sum total for train validate and test median image sizes.
We expect the image preprocessing to even this out to some extent.
The shape of the preprocessing image tensors is (224,224,3).
As a large jpeg image file of many pixels is converted to a tensor,
we expect to lose information in a way that balances the data.

Data Exloration and Visualization, Image File Shape

In [12]:
# build a shape dataframe
def findshape(files,breeds,dset):
    '''
    import image files, breeds, dataset nickname
    load image and parse shape into categories
    return dataframe
    '''
    names = []
    heights = []
    widths = []
    aspects = []
    dsets = []
    for f,b in zip(files, breeds):
        try:
            fdata = mplim.imread(f)
            h,w,d = fdata.shape
            names.append(b)
            heights.append(h)
            widths.append(w)
            aspects.append(round(h/w,2))
            dsets.append(dset)
        except:
            print('Error loading: ' + f)
    df_shape = pd.DataFrame.from_dict({'name': names,
                                       'height': heights,
                                       'width': widths,
                                       'aspect': aspects,
                                       'dataset': dsets,
                                      })
    return df_shape

dfs_train = findshape(train_files, train_breeds,'train')
dfs_valid = findshape(valid_files, valid_breeds,'valid')
dfx_test = findshape(test_files, test_breeds,'test')
df_shape = pd.concat([dfs_train,dfs_valid,dfx_test], ignore_index=True)
df_shape.info()
Error loading: ../../../data/dog_images/train/098.Leonberger/Leonberger_06571.jpg
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8350 entries, 0 to 8349
Data columns (total 5 columns):
name       8350 non-null object
height     8350 non-null int64
width      8350 non-null int64
aspect     8350 non-null float64
dataset    8350 non-null object
dtypes: float64(1), int64(2), object(2)
memory usage: 326.2+ KB
In [13]:
# Show Statistics on Shape
df_shape.describe()
Out[13]:
height width aspect
count 8350.000000 8350.000000 8350.000000
mean 529.016287 566.977844 0.990522
std 333.207284 388.997792 0.301933
min 113.000000 105.000000 0.350000
25% 360.000000 375.000000 0.750000
50% 467.000000 500.000000 0.890000
75% 600.000000 640.000000 1.270000
max 4003.000000 4278.000000 2.520000

Image shape Reflection:

The average Height to Width Aspect ratio is 1.
That is, the average image is square shape.
The tallest image has a height ~2.5 times its width.
The widest image has a height ~0.3 times its width.
The median aspect ratio is less than one.
This suggests images tend to be more landscape format,
than portrait format.
However, there could be situations of square images nested
inside rectangular format files, where outlier pixels
are not contributing information of interest.

In [14]:
# Plot Aspect Ratio
fig, ax = plt.subplots(1,1, figsize=(8, 5), dpi=120)
bins = np.arange(0.2,2.8, 0.2)
ax = sb.distplot(df_shape.aspect, bins=bins, hist_kws= dict(edgecolor="k"))
ax.set(xlabel='Aspect Ratio', ylabel='Frequency')
ax.set_xticks(bins[:-1]+0.1)
ax.set_title('Image File Shapes: Height to Width Aspect Ratios')
plt.show()

Visualization Reflection:

There is a right skew typical when the median or mode is less than the mean.
As the image tensor is square, some pixel data may be cropped or distorted.
A preprocessing step of scaling images on image load relates to this.


Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [15]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[11])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.axis('off')
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [16]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    '''
    import the image path
    convert path to image object
    convert image to grayscale
    classify the image as containing a face or not
    return boolean result of classification
    '''
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

  1. The percentage of human faces found in the first 100 human pictures is 100.
  2. The percentage of human faces found in the first 100 dog pictures is 11.
In [17]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
percent_hfhp = np.sum(list(map(face_detector,human_files_short)))
percent_hfdp = np.sum(list(map(face_detector,dog_files_short)))
print('percent human faces found in human pics = ', percent_hfhp )
print('percent human faces found in dog pics = ', percent_hfdp )
percent human faces found in human pics =  100
percent human faces found in dog pics =  11

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

This seems a reasonable expectation given that the model is trained consistent to this expectation.
For example, a human wears clothes. It is conceivable that some clothes appear dog like in nature.
However, a human face is used here as a differentiating factor that distinguishes a human presence.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [18]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
def face_detector2(img_path):
    '''
    input image path
    convert path to image object
    convert object to grayscale
    classify based upon refined hyperparameters
    return boolean result as containing face or not
    '''
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.15,
        minNeighbors=5,
        minSize=(30, 30),
    )
    return len(faces) > 0

percent_hfhp2 = np.sum(list(map(face_detector2,human_files_short)))
percent_hfdp2 = np.sum(list(map(face_detector2,dog_files_short)))
print('Upgraded Human Face Detection Attempt')
print('percent human faces found in human pics = ', percent_hfhp2 )
print('percent human faces found in dog pics = ', percent_hfdp2 )
Upgraded Human Face Detection Attempt
percent human faces found in human pics =  99
percent human faces found in dog pics =  2

Evolved Detector Reflection:

The scale factor hyer parameter was changed from 1.1 to 1.5,
this has the effect of scaling the image more to find features.
This degraded the human face performance but improved
the dog pic performance significantly.
The end algo has a hierarchical sequence of looking for dogs,
then if it doesn't find a dog, to look for a human.
In the case it misses a dog, we don't want it to make
a second mistake of finding a human in a dog picture.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [19]:
from keras.applications.resnet50 import ResNet50
# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 1s 0us/step

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [20]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    '''
    input image path
    load image
    render into compatible tensor
    return tensor
    '''
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224),
                         interpolation = "bicubic")
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    '''
    input list of image paths
    render paths to tensors
    return vertical stack of tensors
    '''
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Preprocessing Reflection

We saw earlier most images are not square.
The default image load scaling format is nearest.
Potentially, improvement in retaining image fidelity
may be attained in using bilinear or bicubic scaling
within the image load preprocessing step. References:
https://keras.io/api/preprocessing/image/
https://en.wikipedia.org/wiki/Comparison_gallery_of_image_scaling_algorithms

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [21]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    '''
    input image path
    convert path to tensor
    preprocess the tensor
    make predictions
    return most probable prediction
    '''
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [22]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    '''
    input image path
    retrieve most probable prediction
    classify prediction as likely a dog
    return boolean result
    '''
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

  1. The percentage of dogs found in the first 100 human pictures is 0.
  2. The percentage of dogs found in the first 100 dog pictures is 100.
In [23]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

percent_dfhp = np.sum(list(map(dog_detector, human_files_short)))
percent_dfdp = np.sum(list(map(dog_detector, dog_files_short)))
print('percent dog faces found in human pics = ', percent_dfhp)
print('percent dog faces found in dog pics = ', percent_dfdp)
percent dog faces found in human pics =  0
percent dog faces found in dog pics =  100

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [24]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:19<00:00, 84.13it/s] 
100%|██████████| 835/835 [00:08<00:00, 93.45it/s] 
100%|██████████| 836/836 [00:08<00:00, 93.93it/s] 

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

Network Outline:

  1. Squeeze out spatial information: six layers consist of a 2D convolutional layer followed by a max pooling layer. This >provides spatial invariance of dog breed features in identifying the dog breed, meaning the key features can move around >within the picture frame without the dog breed features escaping the classifier.
  2. Flatten 2D inputs to 1D output: The 2D output of the last pooling layer is flattened into 1D in the 7th layer, as a bridge >toward a 1D output format.
  3. Neurally link the output: Two Dense layers separated by a Dropout layer are intended to map the convolution layer output >into the classification categories. The Dense layers left to their own device are apt to overtrain the classifier and the >dropout layers act as counter measures against an over training effect, where the network might memorize the train data in a >way it cannot validate well on the test data.
  4. Provide Output Probabilities: The last dense layer contains one entry per target class with a Softmax activation function >that provides output probabilities for the target classes.

These convolution layers with 3x3 masks in strides of 2 followed by
a pooling layer, were found to be useful in the Resnet architecture for
a similar image classification task.
This is why I think this should work well, however the number of layers
is not sufficient to perform as well as Resnet.

In [25]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(filters=32, kernel_size=3, strides=2, 
                 padding='same', activation='relu',input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=3, strides=2,
                 padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=128, kernel_size=3, strides=2,
                 padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 112, 112, 32)      896       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 28, 28, 64)        18496     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 14, 14, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 7, 7, 128)         73856     
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 3, 3, 128)         0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 1152)              0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 1152)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 256)               295168    
_________________________________________________________________
dropout_2 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               34181     
=================================================================
Total params: 422,597
Trainable params: 422,597
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [26]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [27]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.
epochs = 15

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/15
6640/6680 [============================>.] - ETA: 0s - loss: 4.8517 - acc: 0.0134Epoch 00001: val_loss improved from inf to 4.72978, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 9s 1ms/step - loss: 4.8503 - acc: 0.0136 - val_loss: 4.7298 - val_acc: 0.0347
Epoch 2/15
6660/6680 [============================>.] - ETA: 0s - loss: 4.5008 - acc: 0.0429Epoch 00002: val_loss improved from 4.72978 to 4.34379, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 9s 1ms/step - loss: 4.5006 - acc: 0.0431 - val_loss: 4.3438 - val_acc: 0.0527
Epoch 3/15
6660/6680 [============================>.] - ETA: 0s - loss: 4.2080 - acc: 0.0674Epoch 00003: val_loss improved from 4.34379 to 4.24268, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 9s 1ms/step - loss: 4.2065 - acc: 0.0675 - val_loss: 4.2427 - val_acc: 0.0551
Epoch 4/15
6660/6680 [============================>.] - ETA: 0s - loss: 3.9952 - acc: 0.0862Epoch 00004: val_loss improved from 4.24268 to 4.06832, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 9s 1ms/step - loss: 3.9959 - acc: 0.0865 - val_loss: 4.0683 - val_acc: 0.0838
Epoch 5/15
6660/6680 [============================>.] - ETA: 0s - loss: 3.8117 - acc: 0.1083Epoch 00005: val_loss improved from 4.06832 to 3.93361, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 9s 1ms/step - loss: 3.8123 - acc: 0.1082 - val_loss: 3.9336 - val_acc: 0.0922
Epoch 6/15
6640/6680 [============================>.] - ETA: 0s - loss: 3.6334 - acc: 0.1419Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 3.6335 - acc: 0.1424 - val_loss: 3.9958 - val_acc: 0.1018
Epoch 7/15
6640/6680 [============================>.] - ETA: 0s - loss: 3.4284 - acc: 0.1770Epoch 00007: val_loss improved from 3.93361 to 3.85002, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 9s 1ms/step - loss: 3.4271 - acc: 0.1774 - val_loss: 3.8500 - val_acc: 0.1090
Epoch 8/15
6660/6680 [============================>.] - ETA: 0s - loss: 3.2390 - acc: 0.2119Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 3.2385 - acc: 0.2123 - val_loss: 3.9604 - val_acc: 0.1186
Epoch 9/15
6620/6680 [============================>.] - ETA: 0s - loss: 3.0263 - acc: 0.2517Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 3.0257 - acc: 0.2516 - val_loss: 4.0723 - val_acc: 0.0994
Epoch 10/15
6640/6680 [============================>.] - ETA: 0s - loss: 2.8117 - acc: 0.2989Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 2.8121 - acc: 0.2991 - val_loss: 3.9393 - val_acc: 0.1054
Epoch 11/15
6640/6680 [============================>.] - ETA: 0s - loss: 2.5982 - acc: 0.3444Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 2.5974 - acc: 0.3442 - val_loss: 4.0260 - val_acc: 0.1281
Epoch 12/15
6620/6680 [============================>.] - ETA: 0s - loss: 2.3954 - acc: 0.3743Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 2.3945 - acc: 0.3750 - val_loss: 4.2103 - val_acc: 0.1281
Epoch 13/15
6660/6680 [============================>.] - ETA: 0s - loss: 2.1916 - acc: 0.4215Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 2.1921 - acc: 0.4210 - val_loss: 4.0976 - val_acc: 0.1329
Epoch 14/15
6640/6680 [============================>.] - ETA: 0s - loss: 1.9871 - acc: 0.4643Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 1.9870 - acc: 0.4647 - val_loss: 4.4109 - val_acc: 0.1269
Epoch 15/15
6640/6680 [============================>.] - ETA: 0s - loss: 1.7880 - acc: 0.5125Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 9s 1ms/step - loss: 1.7848 - acc: 0.5135 - val_loss: 4.4886 - val_acc: 0.1257
Out[27]:
<keras.callbacks.History at 0x7fbd2ea7b0f0>

Load the Model with the Best Validation Loss

In [28]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [29]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 12.6794%
In [30]:
# Print classification report on test data
print(classification_report(np.argmax(test_targets, axis=1), 
                            dog_breed_predictions, 
                            target_names=nnames))
                                    precision    recall  f1-score   support

                     Affenpinscher       0.12      0.25      0.16         8
                      Afghan_hound       0.00      0.00      0.00         8
                  Airedale_terrier       0.18      0.50      0.26         6
                             Akita       0.13      0.25      0.17         8
                  Alaskan_malamute       0.12      0.10      0.11        10
               American_eskimo_dog       0.17      0.12      0.14         8
                 American_foxhound       0.06      0.14      0.08         7
    American_staffordshire_terrier       0.00      0.00      0.00         8
            American_water_spaniel       0.17      0.50      0.25         4
            Anatolian_shepherd_dog       0.00      0.00      0.00         6
             Australian_cattle_dog       0.08      0.11      0.10         9
               Australian_shepherd       1.00      0.11      0.20         9
                Australian_terrier       0.00      0.00      0.00         6
                           Basenji       0.25      0.11      0.15         9
                      Basset_hound       0.21      0.50      0.29        10
                            Beagle       0.33      0.50      0.40         8
                    Bearded_collie       0.00      0.00      0.00         8
                         Beauceron       0.50      0.29      0.36         7
                Bedlington_terrier       0.00      0.00      0.00         6
                  Belgian_malinois       0.18      0.25      0.21         8
                  Belgian_sheepdog       0.22      0.25      0.24         8
                  Belgian_tervuren       0.00      0.00      0.00         6
              Bernese_mountain_dog       0.38      0.62      0.48         8
                      Bichon_frise       0.17      0.25      0.20         8
           Black_and_tan_coonhound       0.33      0.25      0.29         4
             Black_russian_terrier       1.00      0.20      0.33         5
                        Bloodhound       0.43      0.38      0.40         8
                Bluetick_coonhound       0.00      0.00      0.00         4
                     Border_collie       0.40      0.60      0.48        10
                    Border_terrier       0.67      0.57      0.62         7
                            Borzoi       0.00      0.00      0.00         7
                    Boston_terrier       0.12      0.25      0.17         8
              Bouvier_des_flandres       0.00      0.00      0.00         5
                             Boxer       0.06      0.12      0.08         8
                    Boykin_spaniel       0.00      0.00      0.00         6
                            Briard       0.00      0.00      0.00         8
                          Brittany       0.00      0.00      0.00         6
                  Brussels_griffon       0.00      0.00      0.00         7
                      Bull_terrier       0.00      0.00      0.00         9
                           Bulldog       0.25      0.14      0.18         7
                       Bullmastiff       0.00      0.00      0.00         9
                     Cairn_terrier       0.06      0.25      0.10         8
                        Canaan_dog       0.00      0.00      0.00         6
                        Cane_corso       0.18      0.50      0.27         8
              Cardigan_welsh_corgi       0.00      0.00      0.00         7
     Cavalier_king_charles_spaniel       0.00      0.00      0.00         9
          Chesapeake_bay_retriever       0.14      0.29      0.19         7
                         Chihuahua       0.00      0.00      0.00         7
                   Chinese_crested       0.00      0.00      0.00         6
                  Chinese_shar-pei       0.00      0.00      0.00         6
                         Chow_chow       0.17      0.25      0.20         8
                   Clumber_spaniel       0.00      0.00      0.00         6
                    Cocker_spaniel       0.00      0.00      0.00         6
                            Collie       0.07      0.14      0.09         7
            Curly-coated_retriever       0.12      0.14      0.13         7
                         Dachshund       0.10      0.11      0.11         9
                         Dalmatian       0.14      0.67      0.23         9
            Dandie_dinmont_terrier       0.08      0.14      0.10         7
                 Doberman_pinscher       0.00      0.00      0.00         6
                 Dogue_de_bordeaux       0.00      0.00      0.00         8
            English_cocker_spaniel       0.00      0.00      0.00         8
                    English_setter       0.00      0.00      0.00         6
          English_springer_spaniel       0.00      0.00      0.00         7
               English_toy_spaniel       0.00      0.00      0.00         5
          Entlebucher_mountain_dog       0.00      0.00      0.00         5
                     Field_spaniel       0.00      0.00      0.00         4
                     Finnish_spitz       0.00      0.00      0.00         4
             Flat-coated_retriever       0.00      0.00      0.00         8
                    French_bulldog       0.00      0.00      0.00         7
                   German_pinscher       0.20      0.33      0.25         6
               German_shepherd_dog       0.11      0.12      0.12         8
        German_shorthaired_pointer       0.00      0.00      0.00         6
         German_wirehaired_pointer       0.00      0.00      0.00         5
                   Giant_schnauzer       0.25      0.20      0.22         5
             Glen_of_imaal_terrier       0.00      0.00      0.00         5
                  Golden_retriever       0.00      0.00      0.00         8
                     Gordon_setter       0.00      0.00      0.00         5
                        Great_dane       0.00      0.00      0.00         5
                    Great_pyrenees       0.12      0.12      0.12         8
        Greater_swiss_mountain_dog       0.00      0.00      0.00         5
                         Greyhound       0.00      0.00      0.00         7
                          Havanese       0.10      0.12      0.11         8
                      Ibizan_hound       0.21      0.50      0.30         6
                Icelandic_sheepdog       0.00      0.00      0.00         6
        Irish_red_and_white_setter       0.00      0.00      0.00         4
                      Irish_setter       0.19      0.57      0.29         7
                     Irish_terrier       0.12      0.12      0.12         8
               Irish_water_spaniel       0.27      0.50      0.35         6
                   Irish_wolfhound       0.17      0.14      0.15         7
                 Italian_greyhound       0.00      0.00      0.00         8
                     Japanese_chin       0.22      0.29      0.25         7
                          Keeshond       0.00      0.00      0.00         5
                Kerry_blue_terrier       0.00      0.00      0.00         4
                          Komondor       0.00      0.00      0.00         5
                            Kuvasz       0.00      0.00      0.00         6
                Labrador_retriever       0.00      0.00      0.00         5
                  Lakeland_terrier       0.00      0.00      0.00         6
                        Leonberger       0.00      0.00      0.00         5
                        Lhasa_apso       0.17      0.20      0.18         5
                           Lowchen       0.00      0.00      0.00         4
                           Maltese       0.00      0.00      0.00         6
                Manchester_terrier       0.00      0.00      0.00         3
                           Mastiff       0.50      0.14      0.22         7
               Miniature_schnauzer       0.00      0.00      0.00         5
                Neapolitan_mastiff       0.00      0.00      0.00         4
                      Newfoundland       0.00      0.00      0.00         6
                   Norfolk_terrier       0.00      0.00      0.00         6
                  Norwegian_buhund       0.00      0.00      0.00         3
                Norwegian_elkhound       0.00      0.00      0.00         5
               Norwegian_lundehund       0.00      0.00      0.00         4
                   Norwich_terrier       0.00      0.00      0.00         5
Nova_scotia_duck_tolling_retriever       0.00      0.00      0.00         7
              Old_english_sheepdog       0.00      0.00      0.00         5
                        Otterhound       0.00      0.00      0.00         4
                          Papillon       0.12      0.38      0.18         8
            Parson_russell_terrier       0.00      0.00      0.00         4
                         Pekingese       0.00      0.00      0.00         6
              Pembroke_welsh_corgi       0.22      0.29      0.25         7
      Petit_basset_griffon_vendeen       0.00      0.00      0.00         4
                     Pharaoh_hound       0.00      0.00      0.00         5
                             Plott       0.00      0.00      0.00         3
                           Pointer       0.00      0.00      0.00         4
                        Pomeranian       0.00      0.00      0.00         5
                            Poodle       0.00      0.00      0.00         6
              Portuguese_water_dog       0.00      0.00      0.00         4
                     Saint_bernard       0.00      0.00      0.00         3
                     Silky_terrier       0.25      0.40      0.31         5
                Smooth_fox_terrier       0.00      0.00      0.00         4
                   Tibetan_mastiff       0.25      0.17      0.20         6
            Welsh_springer_spaniel       0.00      0.00      0.00         5
       Wirehaired_pointing_griffon       0.00      0.00      0.00         3
                    Xoloitzcuintli       0.00      0.00      0.00         3
                 Yorkshire_terrier       0.00      0.00      0.00         4

                       avg / total       0.10      0.13      0.10       836

/opt/conda/lib/python3.6/site-packages/sklearn/metrics/classification.py:1135: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.
  'precision', 'predicted', average, warn_for)

Simple Network Result Evaluation:

The summary yields a warning of many classes without predictions.
The report then sets Precision and F1 to zero, but it may be misleading.
Given more opportunity, predicted samples may occur lifting these positive.
Regardless, the accuracy found of 12% indicates room for improvement.
The Alaskan Malamute and Basset Hound revealed high image count representation.
These two breeds seem to perform better than the other extreme.
The Xoloitzcuintli and Plott have low image counts and zero scores here.


Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [31]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [32]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))
VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [33]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [34]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=90, batch_size=30, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/90
6630/6680 [============================>.] - ETA: 0s - loss: 12.7226 - acc: 0.1029Epoch 00001: val_loss improved from inf to 10.94680, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 227us/step - loss: 12.7177 - acc: 0.1031 - val_loss: 10.9468 - val_acc: 0.1964
Epoch 2/90
6510/6680 [============================>.] - ETA: 0s - loss: 10.3475 - acc: 0.2634Epoch 00002: val_loss improved from 10.94680 to 10.04873, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 10.3233 - acc: 0.2647 - val_loss: 10.0487 - val_acc: 0.2743
Epoch 3/90
6450/6680 [===========================>..] - ETA: 0s - loss: 9.8144 - acc: 0.3309Epoch 00003: val_loss improved from 10.04873 to 9.93227, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 184us/step - loss: 9.8104 - acc: 0.3307 - val_loss: 9.9323 - val_acc: 0.3042
Epoch 4/90
6480/6680 [============================>.] - ETA: 0s - loss: 9.6114 - acc: 0.3582Epoch 00004: val_loss improved from 9.93227 to 9.80115, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 184us/step - loss: 9.6114 - acc: 0.3585 - val_loss: 9.8011 - val_acc: 0.3257
Epoch 5/90
6450/6680 [===========================>..] - ETA: 0s - loss: 9.4939 - acc: 0.3777Epoch 00005: val_loss improved from 9.80115 to 9.68723, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 9.4834 - acc: 0.3778 - val_loss: 9.6872 - val_acc: 0.3377
Epoch 6/90
6420/6680 [===========================>..] - ETA: 0s - loss: 9.3508 - acc: 0.3910Epoch 00006: val_loss improved from 9.68723 to 9.62641, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 9.3579 - acc: 0.3907 - val_loss: 9.6264 - val_acc: 0.3473
Epoch 7/90
6660/6680 [============================>.] - ETA: 0s - loss: 9.2878 - acc: 0.4039Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 9.2889 - acc: 0.4039 - val_loss: 9.6471 - val_acc: 0.3425
Epoch 8/90
6480/6680 [============================>.] - ETA: 0s - loss: 9.2646 - acc: 0.4131Epoch 00008: val_loss improved from 9.62641 to 9.54183, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 9.2582 - acc: 0.4136 - val_loss: 9.5418 - val_acc: 0.3437
Epoch 9/90
6660/6680 [============================>.] - ETA: 0s - loss: 9.2390 - acc: 0.4195Epoch 00009: val_loss improved from 9.54183 to 9.50267, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 9.2403 - acc: 0.4195 - val_loss: 9.5027 - val_acc: 0.3593
Epoch 10/90
6420/6680 [===========================>..] - ETA: 0s - loss: 9.2272 - acc: 0.4213Epoch 00010: val_loss improved from 9.50267 to 9.49837, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 9.2278 - acc: 0.4216 - val_loss: 9.4984 - val_acc: 0.3593
Epoch 11/90
6660/6680 [============================>.] - ETA: 0s - loss: 9.1294 - acc: 0.4249Epoch 00011: val_loss improved from 9.49837 to 9.49107, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 188us/step - loss: 9.1310 - acc: 0.4249 - val_loss: 9.4911 - val_acc: 0.3581
Epoch 12/90
6660/6680 [============================>.] - ETA: 0s - loss: 8.9146 - acc: 0.4320Epoch 00012: val_loss improved from 9.49107 to 9.22987, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 8.9129 - acc: 0.4320 - val_loss: 9.2299 - val_acc: 0.3689
Epoch 13/90
6390/6680 [===========================>..] - ETA: 0s - loss: 8.8191 - acc: 0.4446Epoch 00013: val_loss improved from 9.22987 to 9.22798, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 8.8020 - acc: 0.4457 - val_loss: 9.2280 - val_acc: 0.3701
Epoch 14/90
6660/6680 [============================>.] - ETA: 0s - loss: 8.7586 - acc: 0.4498Epoch 00014: val_loss improved from 9.22798 to 9.07423, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 188us/step - loss: 8.7541 - acc: 0.4501 - val_loss: 9.0742 - val_acc: 0.3689
Epoch 15/90
6450/6680 [===========================>..] - ETA: 0s - loss: 8.5790 - acc: 0.4535Epoch 00015: val_loss improved from 9.07423 to 8.92162, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 8.5634 - acc: 0.4546 - val_loss: 8.9216 - val_acc: 0.3808
Epoch 16/90
6450/6680 [===========================>..] - ETA: 0s - loss: 8.4137 - acc: 0.4668Epoch 00016: val_loss improved from 8.92162 to 8.80692, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 8.4000 - acc: 0.4672 - val_loss: 8.8069 - val_acc: 0.3916
Epoch 17/90
6540/6680 [============================>.] - ETA: 0s - loss: 8.2617 - acc: 0.4745Epoch 00017: val_loss improved from 8.80692 to 8.64843, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 8.2600 - acc: 0.4749 - val_loss: 8.6484 - val_acc: 0.4036
Epoch 18/90
6420/6680 [===========================>..] - ETA: 0s - loss: 8.2071 - acc: 0.4841Epoch 00018: val_loss improved from 8.64843 to 8.61024, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 8.2027 - acc: 0.4841 - val_loss: 8.6102 - val_acc: 0.4108
Epoch 19/90
6390/6680 [===========================>..] - ETA: 0s - loss: 8.1813 - acc: 0.4883Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 8.1834 - acc: 0.4883 - val_loss: 8.6382 - val_acc: 0.4060
Epoch 20/90
6420/6680 [===========================>..] - ETA: 0s - loss: 8.1508 - acc: 0.4896Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 8.1575 - acc: 0.4877 - val_loss: 8.6115 - val_acc: 0.4108
Epoch 21/90
6660/6680 [============================>.] - ETA: 0s - loss: 8.0410 - acc: 0.4949Epoch 00021: val_loss improved from 8.61024 to 8.40249, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 8.0386 - acc: 0.4951 - val_loss: 8.4025 - val_acc: 0.4287
Epoch 22/90
6540/6680 [============================>.] - ETA: 0s - loss: 7.8923 - acc: 0.4950Epoch 00022: val_loss improved from 8.40249 to 8.33458, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 7.9010 - acc: 0.4943 - val_loss: 8.3346 - val_acc: 0.4132
Epoch 23/90
6420/6680 [===========================>..] - ETA: 0s - loss: 7.7888 - acc: 0.5067Epoch 00023: val_loss improved from 8.33458 to 8.28953, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 7.7903 - acc: 0.5067 - val_loss: 8.2895 - val_acc: 0.4120
Epoch 24/90
6450/6680 [===========================>..] - ETA: 0s - loss: 7.7849 - acc: 0.5107Epoch 00024: val_loss improved from 8.28953 to 8.22325, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 7.7640 - acc: 0.5118 - val_loss: 8.2233 - val_acc: 0.4204
Epoch 25/90
6420/6680 [===========================>..] - ETA: 0s - loss: 7.7292 - acc: 0.5140Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 7.7348 - acc: 0.5139 - val_loss: 8.3060 - val_acc: 0.4216
Epoch 26/90
6390/6680 [===========================>..] - ETA: 0s - loss: 7.6511 - acc: 0.5164Epoch 00026: val_loss improved from 8.22325 to 8.14721, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 7.6749 - acc: 0.5150 - val_loss: 8.1472 - val_acc: 0.4335
Epoch 27/90
6390/6680 [===========================>..] - ETA: 0s - loss: 7.5637 - acc: 0.5208Epoch 00027: val_loss improved from 8.14721 to 8.08779, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 7.5591 - acc: 0.5214 - val_loss: 8.0878 - val_acc: 0.4359
Epoch 28/90
6360/6680 [===========================>..] - ETA: 0s - loss: 7.4738 - acc: 0.5302Epoch 00028: val_loss improved from 8.08779 to 8.06288, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 7.5050 - acc: 0.5284 - val_loss: 8.0629 - val_acc: 0.4371
Epoch 29/90
6660/6680 [============================>.] - ETA: 0s - loss: 7.4327 - acc: 0.5300Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 7.4226 - acc: 0.5307 - val_loss: 8.0760 - val_acc: 0.4347
Epoch 30/90
6660/6680 [============================>.] - ETA: 0s - loss: 7.3814 - acc: 0.5372Epoch 00030: val_loss improved from 8.06288 to 7.89053, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 7.3762 - acc: 0.5376 - val_loss: 7.8905 - val_acc: 0.4467
Epoch 31/90
6420/6680 [===========================>..] - ETA: 0s - loss: 7.3839 - acc: 0.5374Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 7.3669 - acc: 0.5385 - val_loss: 7.8945 - val_acc: 0.4527
Epoch 32/90
6630/6680 [============================>.] - ETA: 0s - loss: 7.3506 - acc: 0.5398Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 1s 189us/step - loss: 7.3553 - acc: 0.5395 - val_loss: 7.9298 - val_acc: 0.4431
Epoch 33/90
6420/6680 [===========================>..] - ETA: 0s - loss: 7.2984 - acc: 0.5382Epoch 00033: val_loss improved from 7.89053 to 7.87334, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 7.2859 - acc: 0.5388 - val_loss: 7.8733 - val_acc: 0.4443
Epoch 34/90
6390/6680 [===========================>..] - ETA: 0s - loss: 7.1270 - acc: 0.5462Epoch 00034: val_loss improved from 7.87334 to 7.75806, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 7.1136 - acc: 0.5467 - val_loss: 7.7581 - val_acc: 0.4527
Epoch 35/90
6660/6680 [============================>.] - ETA: 0s - loss: 7.0513 - acc: 0.5560Epoch 00035: val_loss improved from 7.75806 to 7.71755, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 7.0568 - acc: 0.5557 - val_loss: 7.7175 - val_acc: 0.4491
Epoch 36/90
6630/6680 [============================>.] - ETA: 0s - loss: 7.0418 - acc: 0.5582Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 7.0350 - acc: 0.5587 - val_loss: 7.7241 - val_acc: 0.4563
Epoch 37/90
6660/6680 [============================>.] - ETA: 0s - loss: 6.9987 - acc: 0.5584Epoch 00037: val_loss improved from 7.71755 to 7.65964, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 188us/step - loss: 7.0043 - acc: 0.5581 - val_loss: 7.6596 - val_acc: 0.4599
Epoch 38/90
6420/6680 [===========================>..] - ETA: 0s - loss: 6.9289 - acc: 0.5625Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 6.9345 - acc: 0.5618 - val_loss: 7.7376 - val_acc: 0.4455
Epoch 39/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.8657 - acc: 0.5664Epoch 00039: val_loss improved from 7.65964 to 7.63180, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 6.8559 - acc: 0.5671 - val_loss: 7.6318 - val_acc: 0.4479
Epoch 40/90
6660/6680 [============================>.] - ETA: 0s - loss: 6.8122 - acc: 0.5718Epoch 00040: val_loss improved from 7.63180 to 7.58856, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 6.8136 - acc: 0.5717 - val_loss: 7.5886 - val_acc: 0.4539
Epoch 41/90
6420/6680 [===========================>..] - ETA: 0s - loss: 6.7922 - acc: 0.5754Epoch 00041: val_loss improved from 7.58856 to 7.55950, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 6.8007 - acc: 0.5749 - val_loss: 7.5595 - val_acc: 0.4659
Epoch 42/90
6420/6680 [===========================>..] - ETA: 0s - loss: 6.8199 - acc: 0.5740Epoch 00042: val_loss improved from 7.55950 to 7.54613, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 6.7962 - acc: 0.5753 - val_loss: 7.5461 - val_acc: 0.4587
Epoch 43/90
6630/6680 [============================>.] - ETA: 0s - loss: 6.7814 - acc: 0.5772Epoch 00043: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 6.7857 - acc: 0.5768 - val_loss: 7.6028 - val_acc: 0.4539
Epoch 44/90
6420/6680 [===========================>..] - ETA: 0s - loss: 6.7388 - acc: 0.5732Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 6.7065 - acc: 0.5754 - val_loss: 7.5675 - val_acc: 0.4599
Epoch 45/90
6420/6680 [===========================>..] - ETA: 0s - loss: 6.6705 - acc: 0.5816Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 6.6631 - acc: 0.5820 - val_loss: 7.5790 - val_acc: 0.4575
Epoch 46/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.6537 - acc: 0.5812Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 6.6350 - acc: 0.5825 - val_loss: 7.5544 - val_acc: 0.4707
Epoch 47/90
6420/6680 [===========================>..] - ETA: 0s - loss: 6.6045 - acc: 0.5843Epoch 00047: val_loss improved from 7.54613 to 7.54008, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 6.5921 - acc: 0.5852 - val_loss: 7.5401 - val_acc: 0.4623
Epoch 48/90
6660/6680 [============================>.] - ETA: 0s - loss: 6.5732 - acc: 0.5865Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 6.5687 - acc: 0.5867 - val_loss: 7.5820 - val_acc: 0.4575
Epoch 49/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.4684 - acc: 0.5890Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 6.4748 - acc: 0.5886 - val_loss: 7.5554 - val_acc: 0.4503
Epoch 50/90
6480/6680 [============================>.] - ETA: 0s - loss: 6.4416 - acc: 0.5934Epoch 00050: val_loss improved from 7.54008 to 7.41409, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 6.4296 - acc: 0.5943 - val_loss: 7.4141 - val_acc: 0.4671
Epoch 51/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.3898 - acc: 0.5998Epoch 00051: val_loss improved from 7.41409 to 7.41104, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 6.4069 - acc: 0.5984 - val_loss: 7.4110 - val_acc: 0.4743
Epoch 52/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.4194 - acc: 0.5973Epoch 00052: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 6.3947 - acc: 0.5988 - val_loss: 7.5051 - val_acc: 0.4707
Epoch 53/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.4119 - acc: 0.5994Epoch 00053: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 6.3919 - acc: 0.6007 - val_loss: 7.4906 - val_acc: 0.4659
Epoch 54/90
6660/6680 [============================>.] - ETA: 0s - loss: 6.3903 - acc: 0.6009Epoch 00054: val_loss did not improve
6680/6680 [==============================] - 1s 187us/step - loss: 6.3881 - acc: 0.6010 - val_loss: 7.4450 - val_acc: 0.4826
Epoch 55/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.3993 - acc: 0.6006Epoch 00055: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 6.3846 - acc: 0.6016 - val_loss: 7.4380 - val_acc: 0.4731
Epoch 56/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.3579 - acc: 0.6033Epoch 00056: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 6.3748 - acc: 0.6021 - val_loss: 7.4243 - val_acc: 0.4695
Epoch 57/90
6480/6680 [============================>.] - ETA: 0s - loss: 6.2763 - acc: 0.6062Epoch 00057: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 6.3007 - acc: 0.6048 - val_loss: 7.4239 - val_acc: 0.4731
Epoch 58/90
6480/6680 [============================>.] - ETA: 0s - loss: 6.2610 - acc: 0.6077Epoch 00058: val_loss improved from 7.41104 to 7.39898, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 185us/step - loss: 6.2666 - acc: 0.6075 - val_loss: 7.3990 - val_acc: 0.4719
Epoch 59/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.2338 - acc: 0.6106Epoch 00059: val_loss improved from 7.39898 to 7.36239, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 6.2576 - acc: 0.6093 - val_loss: 7.3624 - val_acc: 0.4898
Epoch 60/90
6390/6680 [===========================>..] - ETA: 0s - loss: 6.2805 - acc: 0.6088Epoch 00060: val_loss improved from 7.36239 to 7.32547, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 6.2515 - acc: 0.6106 - val_loss: 7.3255 - val_acc: 0.4826
Epoch 61/90
6660/6680 [============================>.] - ETA: 0s - loss: 6.2341 - acc: 0.6101Epoch 00061: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 6.2348 - acc: 0.6100 - val_loss: 7.3420 - val_acc: 0.4826
Epoch 62/90
6660/6680 [============================>.] - ETA: 0s - loss: 6.1111 - acc: 0.6135Epoch 00062: val_loss improved from 7.32547 to 7.23396, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 188us/step - loss: 6.0976 - acc: 0.6144 - val_loss: 7.2340 - val_acc: 0.4886
Epoch 63/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.9835 - acc: 0.6236Epoch 00063: val_loss improved from 7.23396 to 7.17047, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 187us/step - loss: 6.0123 - acc: 0.6219 - val_loss: 7.1705 - val_acc: 0.4946
Epoch 64/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.9644 - acc: 0.6222Epoch 00064: val_loss improved from 7.17047 to 7.11913, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 188us/step - loss: 5.9333 - acc: 0.6235 - val_loss: 7.1191 - val_acc: 0.4850
Epoch 65/90
6450/6680 [===========================>..] - ETA: 0s - loss: 5.8422 - acc: 0.6296Epoch 00065: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.8390 - acc: 0.6292 - val_loss: 7.1765 - val_acc: 0.4766
Epoch 66/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.8064 - acc: 0.6340Epoch 00066: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.8023 - acc: 0.6338 - val_loss: 7.1761 - val_acc: 0.4814
Epoch 67/90
6480/6680 [============================>.] - ETA: 0s - loss: 5.7853 - acc: 0.6375Epoch 00067: val_loss improved from 7.11913 to 7.08043, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 5.7837 - acc: 0.6376 - val_loss: 7.0804 - val_acc: 0.4886
Epoch 68/90
6420/6680 [===========================>..] - ETA: 0s - loss: 5.7476 - acc: 0.6410Epoch 00068: val_loss improved from 7.08043 to 7.07366, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 5.7811 - acc: 0.6388 - val_loss: 7.0737 - val_acc: 0.4886
Epoch 69/90
6480/6680 [============================>.] - ETA: 0s - loss: 5.7735 - acc: 0.6403Epoch 00069: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.7744 - acc: 0.6403 - val_loss: 7.1210 - val_acc: 0.4862
Epoch 70/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.7729 - acc: 0.6410Epoch 00070: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 5.7773 - acc: 0.6404 - val_loss: 7.0970 - val_acc: 0.4826
Epoch 71/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.7864 - acc: 0.6399Epoch 00071: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 5.7741 - acc: 0.6407 - val_loss: 7.1434 - val_acc: 0.4946
Epoch 72/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.7836 - acc: 0.6404Epoch 00072: val_loss improved from 7.07366 to 7.04819, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 188us/step - loss: 5.7734 - acc: 0.6410 - val_loss: 7.0482 - val_acc: 0.4994
Epoch 73/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.7596 - acc: 0.6418Epoch 00073: val_loss did not improve
6680/6680 [==============================] - 1s 188us/step - loss: 5.7701 - acc: 0.6412 - val_loss: 7.1439 - val_acc: 0.5006
Epoch 74/90
6630/6680 [============================>.] - ETA: 0s - loss: 5.7780 - acc: 0.6407Epoch 00074: val_loss did not improve
6680/6680 [==============================] - 1s 189us/step - loss: 5.7686 - acc: 0.6413 - val_loss: 7.0966 - val_acc: 0.5030
Epoch 75/90
6630/6680 [============================>.] - ETA: 0s - loss: 5.7642 - acc: 0.6415Epoch 00075: val_loss did not improve
6680/6680 [==============================] - 1s 187us/step - loss: 5.7695 - acc: 0.6410 - val_loss: 7.1341 - val_acc: 0.4886
Epoch 76/90
6630/6680 [============================>.] - ETA: 0s - loss: 5.7660 - acc: 0.6415Epoch 00076: val_loss did not improve
6680/6680 [==============================] - 1s 187us/step - loss: 5.7711 - acc: 0.6412 - val_loss: 7.1051 - val_acc: 0.4886
Epoch 77/90
6660/6680 [============================>.] - ETA: 0s - loss: 5.7749 - acc: 0.6408Epoch 00077: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 5.7673 - acc: 0.6413 - val_loss: 7.1327 - val_acc: 0.4946
Epoch 78/90
6420/6680 [===========================>..] - ETA: 0s - loss: 5.7502 - acc: 0.6385Epoch 00078: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.7239 - acc: 0.6403 - val_loss: 7.1786 - val_acc: 0.4874
Epoch 79/90
6420/6680 [===========================>..] - ETA: 0s - loss: 5.6883 - acc: 0.6445Epoch 00079: val_loss did not improve
6680/6680 [==============================] - 1s 186us/step - loss: 5.6576 - acc: 0.6466 - val_loss: 7.1613 - val_acc: 0.4862
Epoch 80/90
6480/6680 [============================>.] - ETA: 0s - loss: 5.6728 - acc: 0.6466Epoch 00080: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.6550 - acc: 0.6478 - val_loss: 7.0819 - val_acc: 0.4946
Epoch 81/90
6420/6680 [===========================>..] - ETA: 0s - loss: 5.6251 - acc: 0.6500Epoch 00081: val_loss improved from 7.04819 to 6.92521, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s 186us/step - loss: 5.6523 - acc: 0.6484 - val_loss: 6.9252 - val_acc: 0.5018
Epoch 82/90
6480/6680 [============================>.] - ETA: 0s - loss: 5.6555 - acc: 0.6486Epoch 00082: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.6479 - acc: 0.6491 - val_loss: 7.0897 - val_acc: 0.4874
Epoch 83/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.6619 - acc: 0.6476Epoch 00083: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 5.6501 - acc: 0.6484 - val_loss: 7.0150 - val_acc: 0.4958
Epoch 84/90
6450/6680 [===========================>..] - ETA: 0s - loss: 5.6103 - acc: 0.6512Epoch 00084: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.6488 - acc: 0.6488 - val_loss: 7.0373 - val_acc: 0.4970
Epoch 85/90
6660/6680 [============================>.] - ETA: 0s - loss: 5.6515 - acc: 0.6488Epoch 00085: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 5.6491 - acc: 0.6490 - val_loss: 7.0124 - val_acc: 0.4982
Epoch 86/90
6390/6680 [===========================>..] - ETA: 0s - loss: 5.6452 - acc: 0.6490Epoch 00086: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 5.6487 - acc: 0.6488 - val_loss: 6.9482 - val_acc: 0.5078
Epoch 87/90
6510/6680 [============================>.] - ETA: 0s - loss: 5.6894 - acc: 0.6465Epoch 00087: val_loss did not improve
6680/6680 [==============================] - 1s 183us/step - loss: 5.6484 - acc: 0.6491 - val_loss: 6.9313 - val_acc: 0.4982
Epoch 88/90
6420/6680 [===========================>..] - ETA: 0s - loss: 5.6194 - acc: 0.6509Epoch 00088: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 5.6493 - acc: 0.6491 - val_loss: 6.9629 - val_acc: 0.5054
Epoch 89/90
6450/6680 [===========================>..] - ETA: 0s - loss: 5.6298 - acc: 0.6504Epoch 00089: val_loss did not improve
6680/6680 [==============================] - 1s 185us/step - loss: 5.6476 - acc: 0.6493 - val_loss: 6.9618 - val_acc: 0.5078
Epoch 90/90
6420/6680 [===========================>..] - ETA: 0s - loss: 5.6341 - acc: 0.6500Epoch 00090: val_loss did not improve
6680/6680 [==============================] - 1s 184us/step - loss: 5.6489 - acc: 0.6491 - val_loss: 7.0363 - val_acc: 0.5066
Out[34]:
<keras.callbacks.History at 0x7fbd2d8d21d0>

Load the Model with the Best Validation Loss

In [35]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [36]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 50.9569%
In [37]:
# Print classification report on test data
print(classification_report(np.argmax(test_targets, axis=1), 
                            VGG16_predictions, 
                            target_names=nnames))
                                    precision    recall  f1-score   support

                     Affenpinscher       0.86      0.75      0.80         8
                      Afghan_hound       0.44      0.50      0.47         8
                  Airedale_terrier       0.83      0.83      0.83         6
                             Akita       0.00      0.00      0.00         8
                  Alaskan_malamute       0.00      0.00      0.00        10
               American_eskimo_dog       0.89      1.00      0.94         8
                 American_foxhound       0.00      0.00      0.00         7
    American_staffordshire_terrier       0.70      0.88      0.78         8
            American_water_spaniel       0.50      0.25      0.33         4
            Anatolian_shepherd_dog       0.24      0.67      0.35         6
             Australian_cattle_dog       0.64      0.78      0.70         9
               Australian_shepherd       1.00      0.78      0.88         9
                Australian_terrier       0.55      1.00      0.71         6
                           Basenji       0.00      0.00      0.00         9
                      Basset_hound       0.53      0.80      0.64        10
                            Beagle       0.00      0.00      0.00         8
                    Bearded_collie       0.00      0.00      0.00         8
                         Beauceron       0.00      0.00      0.00         7
                Bedlington_terrier       0.86      1.00      0.92         6
                  Belgian_malinois       0.00      0.00      0.00         8
                  Belgian_sheepdog       0.60      0.75      0.67         8
                  Belgian_tervuren       0.00      0.00      0.00         6
              Bernese_mountain_dog       0.67      1.00      0.80         8
                      Bichon_frise       0.00      0.00      0.00         8
           Black_and_tan_coonhound       0.60      0.75      0.67         4
             Black_russian_terrier       0.67      0.40      0.50         5
                        Bloodhound       0.67      1.00      0.80         8
                Bluetick_coonhound       0.67      1.00      0.80         4
                     Border_collie       0.90      0.90      0.90        10
                    Border_terrier       0.00      0.00      0.00         7
                            Borzoi       0.00      0.00      0.00         7
                    Boston_terrier       1.00      1.00      1.00         8
              Bouvier_des_flandres       0.00      0.00      0.00         5
                             Boxer       0.50      0.88      0.64         8
                    Boykin_spaniel       0.00      0.00      0.00         6
                            Briard       0.55      0.75      0.63         8
                          Brittany       0.71      0.83      0.77         6
                  Brussels_griffon       0.58      1.00      0.74         7
                      Bull_terrier       0.53      1.00      0.69         9
                           Bulldog       0.00      0.00      0.00         7
                       Bullmastiff       0.00      0.00      0.00         9
                     Cairn_terrier       0.00      0.00      0.00         8
                        Canaan_dog       0.30      0.50      0.37         6
                        Cane_corso       0.47      1.00      0.64         8
              Cardigan_welsh_corgi       0.50      0.43      0.46         7
     Cavalier_king_charles_spaniel       0.00      0.00      0.00         9
          Chesapeake_bay_retriever       0.71      0.71      0.71         7
                         Chihuahua       0.60      0.86      0.71         7
                   Chinese_crested       0.56      0.83      0.67         6
                  Chinese_shar-pei       0.00      0.00      0.00         6
                         Chow_chow       0.00      0.00      0.00         8
                   Clumber_spaniel       0.35      1.00      0.52         6
                    Cocker_spaniel       0.26      1.00      0.41         6
                            Collie       0.62      0.71      0.67         7
            Curly-coated_retriever       0.62      0.71      0.67         7
                         Dachshund       0.50      1.00      0.67         9
                         Dalmatian       1.00      0.89      0.94         9
            Dandie_dinmont_terrier       0.00      0.00      0.00         7
                 Doberman_pinscher       0.80      0.67      0.73         6
                 Dogue_de_bordeaux       0.73      1.00      0.84         8
            English_cocker_spaniel       0.00      0.00      0.00         8
                    English_setter       0.50      0.50      0.50         6
          English_springer_spaniel       0.00      0.00      0.00         7
               English_toy_spaniel       0.00      0.00      0.00         5
          Entlebucher_mountain_dog       0.00      0.00      0.00         5
                     Field_spaniel       0.00      0.00      0.00         4
                     Finnish_spitz       0.14      0.25      0.18         4
             Flat-coated_retriever       1.00      0.75      0.86         8
                    French_bulldog       0.54      1.00      0.70         7
                   German_pinscher       0.36      0.83      0.50         6
               German_shepherd_dog       0.29      0.75      0.41         8
        German_shorthaired_pointer       0.00      0.00      0.00         6
         German_wirehaired_pointer       0.38      0.60      0.46         5
                   Giant_schnauzer       0.50      0.60      0.55         5
             Glen_of_imaal_terrier       0.36      0.80      0.50         5
                  Golden_retriever       0.37      0.88      0.52         8
                     Gordon_setter       0.38      1.00      0.56         5
                        Great_dane       0.50      0.40      0.44         5
                    Great_pyrenees       0.70      0.88      0.78         8
        Greater_swiss_mountain_dog       0.00      0.00      0.00         5
                         Greyhound       0.44      1.00      0.61         7
                          Havanese       0.21      0.62      0.31         8
                      Ibizan_hound       0.00      0.00      0.00         6
                Icelandic_sheepdog       0.19      0.67      0.30         6
        Irish_red_and_white_setter       0.00      0.00      0.00         4
                      Irish_setter       0.00      0.00      0.00         7
                     Irish_terrier       0.86      0.75      0.80         8
               Irish_water_spaniel       0.57      0.67      0.62         6
                   Irish_wolfhound       0.00      0.00      0.00         7
                 Italian_greyhound       0.88      0.88      0.88         8
                     Japanese_chin       0.00      0.00      0.00         7
                          Keeshond       1.00      1.00      1.00         5
                Kerry_blue_terrier       0.23      0.75      0.35         4
                          Komondor       0.00      0.00      0.00         5
                            Kuvasz       0.60      0.50      0.55         6
                Labrador_retriever       0.42      1.00      0.59         5
                  Lakeland_terrier       0.60      0.50      0.55         6
                        Leonberger       0.00      0.00      0.00         5
                        Lhasa_apso       0.38      0.60      0.46         5
                           Lowchen       0.00      0.00      0.00         4
                           Maltese       0.40      0.67      0.50         6
                Manchester_terrier       0.00      0.00      0.00         3
                           Mastiff       0.00      0.00      0.00         7
               Miniature_schnauzer       0.83      1.00      0.91         5
                Neapolitan_mastiff       0.80      1.00      0.89         4
                      Newfoundland       0.67      1.00      0.80         6
                   Norfolk_terrier       0.33      0.67      0.44         6
                  Norwegian_buhund       0.00      0.00      0.00         3
                Norwegian_elkhound       0.40      0.80      0.53         5
               Norwegian_lundehund       0.43      0.75      0.55         4
                   Norwich_terrier       0.00      0.00      0.00         5
Nova_scotia_duck_tolling_retriever       0.55      0.86      0.67         7
              Old_english_sheepdog       0.00      0.00      0.00         5
                        Otterhound       0.00      0.00      0.00         4
                          Papillon       0.00      0.00      0.00         8
            Parson_russell_terrier       0.50      1.00      0.67         4
                         Pekingese       0.29      0.83      0.43         6
              Pembroke_welsh_corgi       0.45      0.71      0.56         7
      Petit_basset_griffon_vendeen       0.44      1.00      0.62         4
                     Pharaoh_hound       0.71      1.00      0.83         5
                             Plott       0.50      0.33      0.40         3
                           Pointer       0.30      0.75      0.43         4
                        Pomeranian       0.00      0.00      0.00         5
                            Poodle       0.57      0.67      0.62         6
              Portuguese_water_dog       1.00      0.25      0.40         4
                     Saint_bernard       0.00      0.00      0.00         3
                     Silky_terrier       0.56      1.00      0.71         5
                Smooth_fox_terrier       0.00      0.00      0.00         4
                   Tibetan_mastiff       0.00      0.00      0.00         6
            Welsh_springer_spaniel       0.29      0.40      0.33         5
       Wirehaired_pointing_griffon       0.50      1.00      0.67         3
                    Xoloitzcuintli       1.00      0.67      0.80         3
                 Yorkshire_terrier       0.00      0.00      0.00         4

                       avg / total       0.38      0.51      0.42       836

/opt/conda/lib/python3.6/site-packages/sklearn/metrics/classification.py:1135: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.
  'precision', 'predicted', average, warn_for)

VGG16 Network Result Evaluation:

The summary yields a warning again, of many classes without predictions.
The report then sets Precision and F1 to zero, but it may be misleading.
In this case the accuracy improved up to 51 percent.
The Alaskan Malamute and Basset Hound revealed high image count representation.
These two breeds however got some big fat zeros here.
By contrast, the Xoloitzcuintli and Plott have low image counts and higher scores.
Possibly the VGG16 pre-train agrees with the bicubic imported image tensors.

Predict Dog Breed with the Model

In [38]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    '''
    input image path
    convert image to tensor
    retrieve output of pre-trained network, aka bottleneck
    make prediction from full connected network
    return prediction of dog breed
    '''
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [39]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_RS50 = bottleneck_features['train']
valid_RS50 = bottleneck_features['valid']
test_RS50 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:
Transfer learning adopts a pre-trained neural network and adapts it to a specific data set.

  1. Interface to the pre-trained network. A fully connected layer takes the existing
    outputs and bridges them over to a fully connected dense layer. Weights assigned
    to this interface are trained to complement optimal bridging. Here the number
    of nodes matches the number of nodes on the pre-trained network.
  2. Convey an output correponding to target classes. A fully connected dense layer
    provides the probability outputs corresponding to the target classes.
    Here, the number of nodes matches the number of output classes of interest.

    This seems an example of interfacing a relatively small data set of similar images
    that complement fine tuning. That is, the images are not so dissimilar than those
    that Resnet50 was originally trained upon, and the data set is small by comparison.

Resnet50 was trained upon Image Net 2012 classification dataset
that contains 1000 classes, trained on 1.28M images, validated on 50K images,
and tested on 100K images. Approximately 120 classes of Resnet were dog breeds.

By comarison, we have ~7K train images, and ~800 each validation and test images,
and 133 classes of dog breeds which is relatively small to Resnet's origin data.

In the case of a small set of similar data, the network is already trained
in a way that is relevant and complements the data. It simply needs an output
interface tailored to the special cases that the data is being used for.
As such, simply the end of the pre-trained network is trained using these
two fully connected layers.

ResNet Paper Reference: https://arxiv.org/abs/1512.03385

In [40]:
### TODO: Define your architecture.
RS50_model = Sequential()
RS50_model.add(GlobalAveragePooling2D(input_shape=train_RS50.shape[1:]))
RS50_model.add(Dense(133, activation='softmax'))
RS50_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 2048)              0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [41]:
### TODO: Compile the model.
RS50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [42]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1,save_best_only=True)

RS50_model.fit(train_RS50, train_targets, 
               validation_data=(valid_RS50, valid_targets),
               epochs=20, batch_size=30, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6480/6680 [============================>.] - ETA: 0s - loss: 1.7688 - acc: 0.5775Epoch 00001: val_loss improved from inf to 0.84545, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s 203us/step - loss: 1.7395 - acc: 0.5835 - val_loss: 0.8454 - val_acc: 0.7497
Epoch 2/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.4504 - acc: 0.8641Epoch 00002: val_loss improved from 0.84545 to 0.71894, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s 159us/step - loss: 0.4477 - acc: 0.8642 - val_loss: 0.7189 - val_acc: 0.7760
Epoch 3/20
6450/6680 [===========================>..] - ETA: 0s - loss: 0.2553 - acc: 0.9202Epoch 00003: val_loss improved from 0.71894 to 0.68606, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s 158us/step - loss: 0.2573 - acc: 0.9198 - val_loss: 0.6861 - val_acc: 0.8060
Epoch 4/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.1663 - acc: 0.9485Epoch 00004: val_loss improved from 0.68606 to 0.67244, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s 158us/step - loss: 0.1651 - acc: 0.9488 - val_loss: 0.6724 - val_acc: 0.8120
Epoch 5/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.1088 - acc: 0.9710Epoch 00005: val_loss improved from 0.67244 to 0.63604, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s 161us/step - loss: 0.1090 - acc: 0.9708 - val_loss: 0.6360 - val_acc: 0.8168
Epoch 6/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0773 - acc: 0.9790Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 1s 156us/step - loss: 0.0767 - acc: 0.9792 - val_loss: 0.6836 - val_acc: 0.8072
Epoch 7/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0519 - acc: 0.9876Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0523 - acc: 0.9871 - val_loss: 0.6559 - val_acc: 0.8251
Epoch 8/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0412 - acc: 0.9901Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0408 - acc: 0.9903 - val_loss: 0.6970 - val_acc: 0.8192
Epoch 9/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0287 - acc: 0.9937Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0290 - acc: 0.9934 - val_loss: 0.7316 - val_acc: 0.8108
Epoch 10/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0225 - acc: 0.9957Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 1s 156us/step - loss: 0.0224 - acc: 0.9958 - val_loss: 0.6984 - val_acc: 0.8287
Epoch 11/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0159 - acc: 0.9963Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0156 - acc: 0.9964 - val_loss: 0.7328 - val_acc: 0.8216
Epoch 12/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0133 - acc: 0.9969Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 1s 158us/step - loss: 0.0133 - acc: 0.9970 - val_loss: 0.7380 - val_acc: 0.8287
Epoch 13/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0110 - acc: 0.9977Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 1s 156us/step - loss: 0.0110 - acc: 0.9978 - val_loss: 0.7812 - val_acc: 0.8216
Epoch 14/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0090 - acc: 0.9980Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0092 - acc: 0.9979 - val_loss: 0.7543 - val_acc: 0.8263
Epoch 15/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0076 - acc: 0.9982Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0075 - acc: 0.9982 - val_loss: 0.7821 - val_acc: 0.8287
Epoch 16/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0060 - acc: 0.9983Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 1s 158us/step - loss: 0.0063 - acc: 0.9981 - val_loss: 0.8110 - val_acc: 0.8287
Epoch 17/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0053 - acc: 0.9983Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0061 - acc: 0.9982 - val_loss: 0.8495 - val_acc: 0.8180
Epoch 18/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0051 - acc: 0.9985Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0051 - acc: 0.9984 - val_loss: 0.8597 - val_acc: 0.8204
Epoch 19/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0043 - acc: 0.9986Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 1s 157us/step - loss: 0.0044 - acc: 0.9985 - val_loss: 0.8580 - val_acc: 0.8299
Epoch 20/20
6510/6680 [============================>.] - ETA: 0s - loss: 0.0052 - acc: 0.9988Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 1s 156us/step - loss: 0.0051 - acc: 0.9988 - val_loss: 0.9235 - val_acc: 0.8263
Out[42]:
<keras.callbacks.History at 0x7fbd2c7042e8>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [43]:
### TODO: Load the model weights with the best validation loss.
RS50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [44]:
### TODO: Calculate classification accuracy on the test dataset.
RS50_predictions = [np.argmax(RS50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_RS50]

# report test accuracy
test_accuracy = 100*np.sum(np.array(RS50_predictions)==np.argmax(test_targets, axis=1))/len(RS50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 82.2967%
In [45]:
# Print classification report on test data
print(classification_report(np.argmax(test_targets, axis=1), 
                            RS50_predictions, 
                            target_names=nnames))
                                    precision    recall  f1-score   support

                     Affenpinscher       1.00      0.75      0.86         8
                      Afghan_hound       1.00      0.75      0.86         8
                  Airedale_terrier       0.62      0.83      0.71         6
                             Akita       0.88      0.88      0.88         8
                  Alaskan_malamute       0.91      1.00      0.95        10
               American_eskimo_dog       1.00      0.88      0.93         8
                 American_foxhound       0.71      0.71      0.71         7
    American_staffordshire_terrier       0.73      1.00      0.84         8
            American_water_spaniel       0.75      0.75      0.75         4
            Anatolian_shepherd_dog       0.56      0.83      0.67         6
             Australian_cattle_dog       1.00      0.78      0.88         9
               Australian_shepherd       0.86      0.67      0.75         9
                Australian_terrier       1.00      0.67      0.80         6
                           Basenji       0.80      0.89      0.84         9
                      Basset_hound       1.00      0.90      0.95        10
                            Beagle       0.88      0.88      0.88         8
                    Bearded_collie       0.86      0.75      0.80         8
                         Beauceron       1.00      0.86      0.92         7
                Bedlington_terrier       1.00      0.83      0.91         6
                  Belgian_malinois       0.89      1.00      0.94         8
                  Belgian_sheepdog       0.75      0.75      0.75         8
                  Belgian_tervuren       0.71      0.83      0.77         6
              Bernese_mountain_dog       1.00      1.00      1.00         8
                      Bichon_frise       1.00      0.88      0.93         8
           Black_and_tan_coonhound       1.00      0.75      0.86         4
             Black_russian_terrier       0.62      1.00      0.77         5
                        Bloodhound       1.00      1.00      1.00         8
                Bluetick_coonhound       1.00      0.50      0.67         4
                     Border_collie       0.91      1.00      0.95        10
                    Border_terrier       1.00      1.00      1.00         7
                            Borzoi       0.83      0.71      0.77         7
                    Boston_terrier       1.00      0.88      0.93         8
              Bouvier_des_flandres       0.80      0.80      0.80         5
                             Boxer       1.00      0.88      0.93         8
                    Boykin_spaniel       1.00      0.67      0.80         6
                            Briard       0.89      1.00      0.94         8
                          Brittany       0.80      0.67      0.73         6
                  Brussels_griffon       0.88      1.00      0.93         7
                      Bull_terrier       1.00      1.00      1.00         9
                           Bulldog       1.00      1.00      1.00         7
                       Bullmastiff       0.78      0.78      0.78         9
                     Cairn_terrier       1.00      1.00      1.00         8
                        Canaan_dog       0.55      1.00      0.71         6
                        Cane_corso       0.88      0.88      0.88         8
              Cardigan_welsh_corgi       0.83      0.71      0.77         7
     Cavalier_king_charles_spaniel       0.80      0.89      0.84         9
          Chesapeake_bay_retriever       1.00      1.00      1.00         7
                         Chihuahua       1.00      0.71      0.83         7
                   Chinese_crested       0.80      0.67      0.73         6
                  Chinese_shar-pei       1.00      0.67      0.80         6
                         Chow_chow       1.00      0.75      0.86         8
                   Clumber_spaniel       1.00      1.00      1.00         6
                    Cocker_spaniel       0.80      0.67      0.73         6
                            Collie       0.78      1.00      0.88         7
            Curly-coated_retriever       0.78      1.00      0.88         7
                         Dachshund       0.69      1.00      0.82         9
                         Dalmatian       1.00      1.00      1.00         9
            Dandie_dinmont_terrier       1.00      0.86      0.92         7
                 Doberman_pinscher       0.67      0.67      0.67         6
                 Dogue_de_bordeaux       0.73      1.00      0.84         8
            English_cocker_spaniel       1.00      0.38      0.55         8
                    English_setter       0.86      1.00      0.92         6
          English_springer_spaniel       0.60      0.86      0.71         7
               English_toy_spaniel       0.60      0.60      0.60         5
          Entlebucher_mountain_dog       0.75      0.60      0.67         5
                     Field_spaniel       0.80      1.00      0.89         4
                     Finnish_spitz       0.60      0.75      0.67         4
             Flat-coated_retriever       0.62      1.00      0.76         8
                    French_bulldog       1.00      1.00      1.00         7
                   German_pinscher       0.45      0.83      0.59         6
               German_shepherd_dog       1.00      0.62      0.77         8
        German_shorthaired_pointer       0.75      1.00      0.86         6
         German_wirehaired_pointer       0.60      0.60      0.60         5
                   Giant_schnauzer       0.33      0.20      0.25         5
             Glen_of_imaal_terrier       1.00      0.60      0.75         5
                  Golden_retriever       0.78      0.88      0.82         8
                     Gordon_setter       0.80      0.80      0.80         5
                        Great_dane       0.80      0.80      0.80         5
                    Great_pyrenees       0.70      0.88      0.78         8
        Greater_swiss_mountain_dog       0.67      0.80      0.73         5
                         Greyhound       0.83      0.71      0.77         7
                          Havanese       0.60      0.75      0.67         8
                      Ibizan_hound       1.00      1.00      1.00         6
                Icelandic_sheepdog       0.50      0.50      0.50         6
        Irish_red_and_white_setter       0.50      0.50      0.50         4
                      Irish_setter       1.00      0.86      0.92         7
                     Irish_terrier       0.88      0.88      0.88         8
               Irish_water_spaniel       1.00      0.83      0.91         6
                   Irish_wolfhound       0.67      0.86      0.75         7
                 Italian_greyhound       1.00      0.88      0.93         8
                     Japanese_chin       0.88      1.00      0.93         7
                          Keeshond       1.00      1.00      1.00         5
                Kerry_blue_terrier       0.75      0.75      0.75         4
                          Komondor       1.00      1.00      1.00         5
                            Kuvasz       0.67      0.33      0.44         6
                Labrador_retriever       0.80      0.80      0.80         5
                  Lakeland_terrier       1.00      0.67      0.80         6
                        Leonberger       1.00      1.00      1.00         5
                        Lhasa_apso       0.50      0.60      0.55         5
                           Lowchen       0.67      0.50      0.57         4
                           Maltese       1.00      0.67      0.80         6
                Manchester_terrier       1.00      0.67      0.80         3
                           Mastiff       0.75      0.86      0.80         7
               Miniature_schnauzer       0.80      0.80      0.80         5
                Neapolitan_mastiff       1.00      0.75      0.86         4
                      Newfoundland       0.75      1.00      0.86         6
                   Norfolk_terrier       0.83      0.83      0.83         6
                  Norwegian_buhund       1.00      0.33      0.50         3
                Norwegian_elkhound       0.80      0.80      0.80         5
               Norwegian_lundehund       1.00      0.75      0.86         4
                   Norwich_terrier       0.56      1.00      0.71         5
Nova_scotia_duck_tolling_retriever       0.88      1.00      0.93         7
              Old_english_sheepdog       0.80      0.80      0.80         5
                        Otterhound       0.80      1.00      0.89         4
                          Papillon       1.00      0.75      0.86         8
            Parson_russell_terrier       0.80      1.00      0.89         4
                         Pekingese       1.00      1.00      1.00         6
              Pembroke_welsh_corgi       0.71      0.71      0.71         7
      Petit_basset_griffon_vendeen       1.00      1.00      1.00         4
                     Pharaoh_hound       1.00      1.00      1.00         5
                             Plott       1.00      0.33      0.50         3
                           Pointer       1.00      0.50      0.67         4
                        Pomeranian       0.57      0.80      0.67         5
                            Poodle       0.56      0.83      0.67         6
              Portuguese_water_dog       1.00      0.25      0.40         4
                     Saint_bernard       1.00      1.00      1.00         3
                     Silky_terrier       1.00      0.80      0.89         5
                Smooth_fox_terrier       1.00      0.75      0.86         4
                   Tibetan_mastiff       1.00      0.50      0.67         6
            Welsh_springer_spaniel       0.57      0.80      0.67         5
       Wirehaired_pointing_griffon       1.00      0.33      0.50         3
                    Xoloitzcuintli       1.00      1.00      1.00         3
                 Yorkshire_terrier       0.60      0.75      0.67         4

                       avg / total       0.85      0.82      0.82       836

RS50 Network Result Evaluation:

The summary yields no warnings, which implies predictions in all classes.
In this case the accuracy improved up to 82% on the test cases.
This agrees well with the validation set suggesting it isn't overtrained.
The avg precision is 85% indicates it is more relevant than irrelevant,
in other words, there are 15% false positives.
The avg recall is 82% indicates the percentage of relevant caught is high,
in other words, there are 18% false negatives.
Returning to accuracy, slightly better than one out of five times,
it slips up on identifying the correct breed of dog depicted within the image.
This may be partially related to inconsistencies in photography and data handling.

Justification Reflection

A sequence of models was built of incrementally improving quality.
The simple model resulted in the worst performance, 11% accurate.
The Pre-Trained VGG16 tailored to these dogs improved, 51% accurate.
The Pre-Trained RS50, which contained dog breed classes to begin with,
was tailored to these dogs and resulted in best performance,
82% accurate.

Unseen to the reader may be the essense of training time.
That is, the RS50 network took immense effort to build.
However, to tailor it to this aim entailed an effort that seems
comparable to the simple network, however perfoms 8 times better.
For this reason, it seems that transfer learning approaches offer
fast tracking advantage in arriving at classification solutions.

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [46]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import *
try:
    # extract bottleneck features
    bottleneck_feature = extract_Resnet50()
    # obtain predicted vector
    predicted_vector = RS50_model.predict(bottleneck_feature)
except:
    pass


def RS50_predict_breed(img_path):
    '''
    input image path
    convert image to tensor
    retrieve output of pre-trained network, aka bottleneck
    make prediction from full connected network
    return prediction of dog breed
    '''
    # extract bottleneck features
    bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = RS50_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

A sample image and output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

This photo looks like an Afghan Hound.

(IMPLEMENTATION) Write your Algorithm

In [49]:
def pic_display(path):
    '''
    load image path
    convert to RGB
    display in RGB
    '''
    img = cv2.imread(path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(cv_rgb)
    plt.axis('off')
    plt.show()

def picture_sort(path):
    '''
    import image path
    display image
    sort image by dog or human
    if dog, figure out the breed
    print sort decision
    '''
    # display
    pic_display(path)
    # sort class and reveal
    dog = dog_detector(path)
    human = face_detector2(path)
    if dog:
        print('A dog detected!')
        prob_breed = RS50_predict_breed(path)
        per_loc = prob_breed.find('.')+1
        print('Possible breed: '+ prob_breed[per_loc:])
    elif human:
        print('A human face detected!')
        prob_breed = RS50_predict_breed(path)
        per_loc = prob_breed.find('.')+1
        print('May share resemblance with: '+ prob_breed[per_loc:])
    else:
        print('Neither a dog nor a human face was detected.')
        
    print('----------------------------------------------')
    print()

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

  1. The output is better than expected.
    Only one error was observed out of eleven attempts.
    The error occurred in what seems like a picture of a dog picture.
    This was recognized as neither a dog nor a human.
    In taking pictures of pictures, the picture fidelity can degrade.
    Potential errors made in dog breed classification seem questionable.
    There's many cross breeds and DNA analysis is needed for accuracy.
  2. Potential improvement in the algorithm include:
    A. Detection of multiple dogs or humans or mix in pictures.
    B. Expansion of classes to include other animal types, i.e. fox, wolf.
    C. Picture fidelity screening to prevent errors.
In [50]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
import os
import glob
import cv2
cwd = os.getcwd()
img_folder = cwd + "/images/*"
pics = glob.glob(img_folder)
for path in pics:
    picture_sort(path)
A human face detected!
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
94658560/94653016 [==============================] - 1s 0us/step
May share resemblance with: English_toy_spaniel
----------------------------------------------

A dog detected!
Possible breed: Welsh_springer_spaniel
----------------------------------------------

A dog detected!
Possible breed: Brittany
----------------------------------------------

A dog detected!
Possible breed: Labrador_retriever
----------------------------------------------

A dog detected!
Possible breed: Curly-coated_retriever
----------------------------------------------

Neither a dog nor a human face was detected.
----------------------------------------------

A dog detected!
Possible breed: Labrador_retriever
----------------------------------------------

A dog detected!
Possible breed: Labrador_retriever
----------------------------------------------

Neither a dog nor a human face was detected.
----------------------------------------------

A human face detected!
May share resemblance with: English_toy_spaniel
----------------------------------------------

A dog detected!
Possible breed: Boykin_spaniel
----------------------------------------------

Conclusion

In this project we tried to solve an image classification problem.
Given an image, if it contains a dog then answer what breed it might be.
Otherwise, if it contains a face then answer what dog breed shares resemblance.
To tackle this problem, we pursued a supervised learing approach.
To do that, we jumped off the shoulders of giants: beloved data curators at Udacity.
The dataset utilized contained over 8000 dog images and 13000 human images.
In taking a close look at dog data, we discovered the image count per breed
varies by a factor of three, the file size varies by a factor of 5, and the
aspect ratio of the pictures varies from wide landscapes to tall portraits.
Using a divide and conquer approach, first a human face detector was built.
This function input an image and returned a true false reply if a face was found.
At the heart of the human face detector works the OpenCV face cascade module.
Furthermore, we built a dog detector using ResNet-50 with imagenet weights.
Both the dog detector and face detector were found to be highly accurate, ~100%.
From there, focus was applied to three classifiers for distinguishing 133 breeds.
A simple Convolutional Neural Network, a Transfer learned VGG16, and a transfer
learned ResNet50. These resulted in accuracies of 11%, 54%, and 81% repectively.
Finally the face and dog detector were combined with the breed classifier
in a way that addressed the crux of the problem, given an image - provide answers.

The successful results revealed by the output demonstrates a classification
approach that likely has advantage over others for compatible classification schemes.
Here a transfer learning approach attained a good result in a relatively short time.
I found it interesting that GPU training appears to progress faster than CPU alone.
The indication of progress seems to affirm problems are solved sooner than later.
I also found it interesting that this is one of the most popular projects.
I attribute much of the success and popularity to the dataset, thanks for that.
There seem many blogs featuring this topic, as if man's best friend came to the rescue.

One improvement idea for this project is based upon the idea garbage in causes
garbage out. That is, the images are screened for some degrees of quality that
are not meant to trick the network. Making a network that classifies well using
clean data is a step toward making a network that works with dirty data.
Potentially an image fidelity classifier is put on the front end to weed out
images that recklessly degrade performance. Another improvement idea relates
to standardizing image input formats, where variation in image sizes are regularized
before undergoing similar scaling routines into tensors. In this case the image
shapes were found widely varying and the scaling to tensor somewhat mysterious,
where imposing data regularization in the interest of reducing variance may improve
classification noise levels. Lastly, full stack implementation of this onto a
mobile phone app, seems beyond the grasp of this notebook - but what if it wasn't?
It would improve the project to deploy on a mobile phone in a way that puts the
solution of this problem into the hands of dog lovers the world over.

Additonal inference routines

In [51]:
import pickle
# pickle dog names
pickle.dump(dog_names, open("dognames.pkl","wb"))
In [52]:
### TODO: Define your architecture.
RS50_infer = Sequential()
RS50_infer.add(GlobalAveragePooling2D(input_shape=(1,1,2048)))
RS50_infer.add(Dense(133, activation='softmax'))
RS50_infer.load_weights('saved_models/weights.best.Resnet50.hdf5')
In [53]:
def RS50_infer_predict(img_path):
    '''
    input image path
    convert image to tensor
    retrieve output of pre-trained network, aka bottleneck
    make prediction from full connected network
    return prediction of dog breed
    '''
    # extract bottleneck features
    bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = RS50_infer.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
In [54]:
def infer_sort(path):
    '''
    import image path
    display image
    sort image by dog or human
    if dog, figure out the breed
    print sort decision
    '''
    # display
    pic_display(path)
    # sort class and reveal
    dog = dog_detector(path)
    human = face_detector2(path)
    if dog:
        print('A dog detected!')
        prob_breed = RS50_infer_predict(path)
        per_loc = prob_breed.find('.')+1
        print('Possible breed: '+ prob_breed[per_loc:])
    elif human:
        print('A human face detected!')
        prob_breed = RS50_infer_predict(path)
        per_loc = prob_breed.find('.')+1
        print('May share resemblance with: '+ prob_breed[per_loc:])
    else:
        print('Error: Neither dog nor human face detected.')
        
    print('----------------------------------------------')
    print()
In [55]:
# images uploaded from phone
cwd = os.getcwd()
img_folder = cwd + "/phone/*"
pics = glob.glob(img_folder)
for path in pics:
    infer_sort(path)
Error: Neither dog nor human face detected.
----------------------------------------------

Error: Neither dog nor human face detected.
----------------------------------------------

A dog detected!
Possible breed: Canaan_dog
----------------------------------------------

Error: Neither dog nor human face detected.
----------------------------------------------

A dog detected!
Possible breed: Chihuahua
----------------------------------------------

A human face detected!
May share resemblance with: Chinese_crested
----------------------------------------------

Error: Neither dog nor human face detected.
----------------------------------------------

Error: Neither dog nor human face detected.
----------------------------------------------

Error: Neither dog nor human face detected.
----------------------------------------------

A human face detected!
May share resemblance with: Dachshund
----------------------------------------------

A human face detected!
May share resemblance with: English_toy_spaniel
----------------------------------------------

Error: Neither dog nor human face detected.
----------------------------------------------

In [ ]: